<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Category;
use think\facade\Db;

class CategoryService extends Service
{

    public function getList($page, $limit, $searchQuery = null)
    {
        $category = Category::where([])->page($page, $limit);
        return [
            'total' => $category->count(),
            'list' => $category->select(),
        ];
    }

    public function save($data, $id = null)
    {
        Db::startTrans();
        try {
            if (empty($id)) {
                Category::create([
                    'name' => $data['name'],
                    'sort' => $data['sort'],
                ]);
            } else {
                $info = Category::where('category_id', $id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $info->save([
                    'name' => $data['name'],
                    'sort' => $data['sort'],
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }

    public function info($id)
    {
        $info = Category::where('category_id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->toArray();
    }


    public function del($id)
    {
        $info = Category::where('category_id', $id)->find();
        if (!$info) {
            throw new BusinessException('类别不存在');
        }
        return $info->delete();
    }
}